<?php

namespace app\api\service;

use think\facade\Db;

class ComboService
{
    public static function getComboList($store_id)
    {
        $comboList = Db::name('combo')
                        ->alias('a')
                        ->field('a.id,a.combo_name,a.combo_image,a.origin_price,a.sell_price,b.grade_name,a.give_coupon,a.give_integral,
                        a.give_balance,a.combo_desc')
                        ->join('user_grade b','a.user_grade_id=b.id')
                        ->withAttr('combo_image',function ($value){
                            return request()->domain() . $value;
                        })->withAttr('give_coupon',function ($value){
                            if (!empty($value)){
                                $rows = json_decode($value,true);
                                $ids = array_column($rows,'coupon_id');
                                $coupons = Db::name('coupon')
                                             ->field('coupon_name,icon,coupon_type,desc')
                                              ->whereIn('id',$ids)
                                             ->select();
                                $arr =[];
                                foreach ($coupons as $k => $v){
                                    $arr[$k]['coupon_name'] = $v['coupon_name'];
                                    $arr[$k]['icon'] = request()->domain().$v['icon'];
                                    $arr[$k]['coupon_type'] = $v['coupon_type'];
                                    $arr[$k]['desc'] = $v['desc'];
                                    $arr[$k]['give_num'] = $rows[$k]['give_num'];
                                }

                                return $arr;
                            }

                            return  [];
                        })->where(['a.store_id' => $store_id,'a.status' =>1,'a.delete_time' =>0])
                        ->select();

        return $comboList;
    }



    public static function findComboDetail($combo_id)
    {
        $combo = Db::name('combo')
                    ->field('id,store_id,combo_name,combo_image,origin_price,sell_price')
                    ->where(['id' => $combo_id,'status' =>1])
                    ->find();

        return $combo;
    }


    public static function saveOrder($data)
    {
        $combo_order_id = Db::name('combo_order')->insertGetId([
              'store_id' => $data['store_id'],
              'order_no' => $data['order_no'],
              'combo_amount' => $data['combo_amount'],
              'combo_id' => $data['combo_id'],
              'status' => 1,
              'create_time' => time()
        ]);

        return $combo_order_id;
    }
}